<template>
  <div class="service-container">
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <h3>报修服务管理</h3>
          <div class="search-toggle-area">
            <el-button class="search-toggle-button" @click="toggleSearchBar">
              <el-icon><Search /></el-icon>
            </el-button>
            <el-form :inline="true" :model="queryParams" class="search-form" :class="{'is-hidden': !showSearchBar}" ref="queryForm">
              <el-form-item label="状态">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 160px;">
                  <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>

      <el-table 
        :data="repairList" 
        style="width: 100%" 
        v-loading="loading"
        border
        stripe
        :header-cell-style="{background:'#f5f7fa', color:'#606266'}"
      >
        <el-table-column prop="repair_id" label="ID" width="80" align="center" header-align="center" />
        <el-table-column prop="applicant_user_name" label="申请用户" width="120" align="center" header-align="center" />
        <el-table-column prop="location" label="报修位置" show-overflow-tooltip align="center" header-align="center" />
        <el-table-column prop="fault_description" label="故障描述" show-overflow-tooltip align="center" header-align="center" />
        <el-table-column prop="application_time" label="申请时间" width="180" align="center" header-align="center" />
        <el-table-column prop="status" label="状态" width="120" align="center" header-align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="handler_user_name" label="处理人" width="120" align="center" header-align="center">
            <template #default="{ row }">
                {{ row.handler_user_name || '暂无' }}
            </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center" header-align="center">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleView(row.repair_id)">查看</el-button>
            <el-button v-if="row.status === '待受理'" type="success" link size="small" @click="handleAssign(row.repair_id)">指派</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="repairList.length === 0 && !loading" description="暂无报修服务数据" class="empty-data-placeholder"></el-empty>

      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, total"
          :total="total"
          :page-size="queryParams.size"
          :current-page="queryParams.current"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="报修详情" width="50%">
      <div v-if="selectedRepair" class="detail-container">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="报修ID">{{ selectedRepair.repair_id }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ selectedRepair.status }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ selectedRepair.applicant_user.username }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ selectedRepair.application_time }}</el-descriptions-item>
          <el-descriptions-item label="报修位置" :span="2">{{ selectedRepair.location }}</el-descriptions-item>
          <el-descriptions-item label="故障描述" :span="2">{{ selectedRepair.fault_description }}</el-descriptions-item>
          <el-descriptions-item label="期望处理时间">{{ selectedRepair.expected_time || '无' }}</el-descriptions-item>
          <el-descriptions-item label="指派处理人">{{ selectedRepair.handler_user ? selectedRepair.handler_user.username : '暂未指派' }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ selectedRepair.completion_time || '未完成' }}</el-descriptions-item>
          <el-descriptions-item label="维修费用">{{ selectedRepair.repair_cost || '无' }}</el-descriptions-item>
          <el-descriptions-item label="维修结果" :span="2">{{ selectedRepair.repair_result || '暂无' }}</el-descriptions-item>
          <el-descriptions-item label="用户评价" :span="2">
            <el-rate v-if="selectedRepair.rating" :model-value="selectedRepair.rating" disabled />
            <p>{{ selectedRepair.review_content || '暂无评价' }}</p>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 指派处理人对话框 -->
    <el-dialog v-model="assignDialogVisible" title="指派处理人" width="30%">
      <el-select v-model="selectedHandlerId" placeholder="请选择维修工" style="width: 100%;">
        <el-option
          v-for="staff in maintenanceStaffList"
          :key="staff.user_id"
          :label="`${staff.name} (${staff.employee_no})`"
          :value="staff.user_id"
        />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAssignment">确认指派</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { getRepairList, getRepairDetail, assignRepairHandler } from '@/api/services';
import { getMaintenanceStaffList } from '@/api/users';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue'

const repairList = ref([]);
const loading = ref(false);
const total = ref(0);
const queryParams = reactive({
  current: 1,
  size: 10,
  status: null, // Example filter
});
const showSearchBar = ref(false);
const statusOptions = ref([
  { value: '待受理', label: '待受理' },
  { value: '处理中', label: '处理中' },
  { value: '已完成', label: '已完成' },
  { value: '已评价', label: '已评价' },
  { value: '已取消', label: '已取消' },
]);

const viewDialogVisible = ref(false);
const selectedRepair = ref(null);

const assignDialogVisible = ref(false);
const currentRepairId = ref(null);
const maintenanceStaffList = ref([]);
const selectedHandlerId = ref(null);

const fetchRepairList = async () => {
  loading.value = true;
  try {
    const response = await getRepairList(queryParams);
    if (response.data && response.data.code === 200) {
        repairList.value = response.data.data.list;
        total.value = response.data.data.total;
    } else {
        repairList.value = [];
        total.value = 0;
    }
  } catch (error) {
    console.error('Failed to fetch repair list:', error);
    ElMessage.error('获取报修列表失败');
  } finally {
    loading.value = false;
  }
};

// 切换搜索栏显示状态
const toggleSearchBar = () => {
  showSearchBar.value = !showSearchBar.value;
};

// 查询按钮点击事件
const handleQuery = () => {
  queryParams.current = 1;
  fetchRepairList();
};

// 重置按钮点击事件
const resetQuery = () => {
  queryParams.status = null;
  handleQuery();
};

const handleView = async (id) => {
  try {
    const response = await getRepairDetail(id);
    if (response.data && response.data.code === 200) {
      selectedRepair.value = response.data.data;
      viewDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.message || '获取详情失败');
    }
  } catch (error) {
    console.error('Failed to fetch repair details:', error);
    ElMessage.error('获取详情失败');
  }
};

const handleAssign = async (id) => {
  const repair = repairList.value.find(item => item.repair_id === id);
  if (repair && repair.status !== '待受理') {
    ElMessage.warning('只有"待受理"状态的报修才能指派。');
    return;
  }
  currentRepairId.value = id;
  selectedHandlerId.value = null; // Reset previous selection
  try {
    const response = await getMaintenanceStaffList();
    if (response.data && response.data.code === 200) {
      maintenanceStaffList.value = response.data.data.list;
      assignDialogVisible.value = true;
    } else {
      ElMessage.error('获取维修工列表失败');
    }
  } catch (error) {
    console.error('Failed to fetch maintenance staff:', error);
    ElMessage.error('获取维修工列表失败');
  }
};

const confirmAssignment = async () => {
  if (!selectedHandlerId.value) {
    ElMessage.warning('请选择一个维修工');
    return;
  }
  try {
    const response = await assignRepairHandler(currentRepairId.value, selectedHandlerId.value);
    if (response.data && response.data.code === 200) {
      ElMessage.success('指派成功');
      assignDialogVisible.value = false;
      fetchRepairList(); // Refresh the list to show changes
    } else {
      ElMessage.error(response.data.message || '指派失败');
    }
  } catch (error) {
    console.error('Failed to assign handler:', error);
    ElMessage.error('指派失败');
  }
};

const handleCurrentChange = (page) => {
  queryParams.current = page;
  fetchRepairList();
};

const getStatusType = (status) => {
  switch (status) {
    case '待受理': return 'warning';
    case '处理中': return 'primary';
    case '已完成': return 'success';
    case '已评价': return 'success';
    case '已取消': return 'info';
    default: return 'info';
  }
}

onMounted(() => {
  fetchRepairList();
});
</script>

<style scoped>
.service-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 80px);
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* 搜索区域 */
.search-toggle-area {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.search-toggle-button {
  font-size: 20px;
  color: #606266;
  align-self: center;
  margin-right: 15px;
  transition: all 0.2s;
  cursor: pointer;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(0, 0, 0, 0.05);
  z-index: 10;
  margin-bottom: 0;
}

.search-toggle-button:hover {
  color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
  border-color: rgba(64, 158, 255, 0.2);
}

.search-form {
  max-width: 1000px;
  width: auto;
  overflow: hidden;
  transition: max-width 0.4s ease-in-out, opacity 0.4s ease-in-out, background-color 0.4s ease-in-out, box-shadow 0.4s ease-in-out, padding 0.4s ease-in-out, margin-left 0.4s ease-in-out, height 0.4s ease-in-out, min-height 0.4s ease-in-out;
  opacity: 1;
  background-color: transparent;
  border-radius: 8px;
  padding: 0 20px;
  box-shadow: none;
  pointer-events: auto;
  margin-left: 15px;
  white-space: nowrap;
  height: 35px;
  min-height: 35px;
}

.search-form.is-hidden {
  max-width: 0;
  opacity: 0;
  padding: 0;
  margin-left: 0;
  height: 0;
  min-height: 0;
  background-color: transparent;
  box-shadow: none;
  pointer-events: none;
}

/* 调整搜索表单项的底部外边距 */
:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  margin-right: 15px;
  display: inline-flex;
  align-items: center;
}

:deep(.search-form .el-form-item__label) {
  padding-right: 8px;
}

:deep(.table-card .el-card__header) {
  background-color: #f9fafc;
  padding: 15px 20px;
}

:deep(.table-card .el-card__body) {
  padding: 20px;
}

.pagination-container {
  margin-top: 25px;
  display: flex;
  justify-content: flex-end;
  padding: 12px 15px;
  background-color: #f9fbfd;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.empty-data-placeholder {
  margin-top: 40px;
}

/* 搜索框el-input优化 */
:deep(.el-input__inner) {
  border-color: #e0e5ed !important;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-input__inner:focus) {
  border-color: rgba(64, 158, 255, 0.4) !important;
}

:deep(.el-input__inner::placeholder) {
  color: #aebccf;
}

/* 按钮el-button优化 */
:deep(.el-button--primary) {
  background-color: rgba(64, 158, 255, 0.1) !important;
  color: #606266 !important;
  border-color: rgba(64, 158, 255, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--primary:hover) {
  background-color: rgba(64, 158, 255, 0.15) !important;
  border-color: rgba(64, 158, 255, 0.3) !important;
}

:deep(.el-button--success) {
  background-color: rgba(103, 194, 58, 0.1) !important;
  color: #67C23A !important;
  border-color: rgba(103, 194, 58, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--success:hover) {
  background-color: rgba(103, 194, 58, 0.15) !important;
  border-color: rgba(103, 194, 58, 0.3) !important;
}

/* Default Button */
:deep(.el-button--default) {
  background-color: #ffffff !important;
  color: #606266 !important;
  border-color: #dcdfe6 !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--default:hover) {
  background-color: #f7f9fa !important;
  border-color: #c8d3dd !important;
}
</style> 